package com.qf.servlet;

import com.qf.service.BooksBorrowService;
import com.qf.service.impl.BooksBorrowServiceImpl;
import com.qf.utils.JsonUtils;
import com.qf.utils.ResultVo;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/booksBorrowServlet")
public class BooksBorrowServlet extends BaseServlet{
    private ResultVo resultVo;
    private BooksBorrowService booksBorrowService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        booksBorrowService = new BooksBorrowServiceImpl();
    }

    public void addBookBorrow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户uid
        String uid = req.getParameter("uid");
        //获取书籍的bid
        String bid = req.getParameter("bid");
        if(uid==null || "".equals(uid)){
            resultVo = ResultVo.error(500,"非法登录");
        }else if(bid==null || "".equals(bid)){
            resultVo = ResultVo.error(500,"传入的书籍不能为空");
        } else {
            int num = booksBorrowService.addBooksBorrow(Integer.parseInt(uid), Integer.parseInt(bid));
            if(num==0){
                resultVo = ResultVo.error(500,"借书异常");
            }else if(num==-1){
                resultVo = ResultVo.error(500,"书已外借，无法借书");
            }else if(num==-2){
                resultVo = ResultVo.error(500,"您没有书卡，不能借书");
            }else {
                resultVo = ResultVo.success(200,"借书成功",num);
            }
        }
        JsonUtils.toJsonString(resultVo,resp);
    }
}
